package com.zsr.chapter05.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author zsr
 * @Description
 * @Date 2021/4/22 12:44
 */
public class Demo6 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        String username = request.getParameter("username");
        //isAutoLogin为null时未选中
        String isAutoLogin = request.getParameter("isAutoLogin");
        PrintWriter out = response.getWriter();

        //未选择自动登录
        if (isAutoLogin == null) {
            if (username == null || username.isEmpty()) {
                out.print("请输入用户名登录");
                //2秒后自动跳转
                response.setHeader("refresh", "2;URL=/javaweb_task_demo/page/chapter05/login.jsp");
            } else if (username.equals("zhangsan")) {
                out.print("您已登录，欢迎您！<a href='/javaweb_task_demo/page/chapter05/login.jsp'>退出<a/>");
            }
        } else {//选中自动登录
            Cookie userNameCookie = null;
            //获取cookie
            for (Cookie cookie : request.getCookies()) {
                if (cookie.getName().equals("username")) {
                    userNameCookie = cookie;
                }
            }
            //如果存在Cookie并值为zhangsan，获取输入了用户名
            if ((userNameCookie != null && userNameCookie.getValue().equals("zhangsan"))) {
                out.print("您已登录，欢迎您！<a href='/javaweb_task_demo/page/chapter05/login.jsp'>退出<a/>");
            }
            //如果Cookie为空，用户名为空
            else if(userNameCookie == null &&(username == null || username.isEmpty())){
                out.print("请输入用户名登录");
                //2秒后自动跳转
                response.setHeader("refresh", "2;URL=/javaweb_task_demo/page/chapter05/login.jsp");
            }
            //如果Cookie为空但是输入了用户名，新建Cookie对象并传回客户端
            else if (userNameCookie == null && username.equals("zhangsan")) {
                Cookie cookie = new Cookie("username", "zhangsan");
                //设置5秒后过期
                cookie.setMaxAge(5);
                response.addCookie(cookie);
                out.print("您已登录，欢迎您！<a href='/javaweb_task_demo/page/chapter05/login.jsp'>退出<a/>");
            }
        }

    }
}
